package com.ujiuye.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理post请求乱码
        req.setCharacterEncoding("UTF-8");
        //响应给浏览器数据乱码的处理
        resp.setContentType("text/html;charset=utf-8");
        //获取请求的统一资源定位符
        String uri = req.getRequestURI();
        //获取不同的部分
        String method = uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf(".do"));
        System.out.println(method);
        //通过反射实现方法的调用
        //1.获取当前实现类的类对象
        Class<? extends BaseServlet> aClass = this.getClass();
        //2.获取当前类的public方法对象
        try {
            Method meth = aClass.getMethod(method,HttpServletRequest.class,HttpServletResponse.class);
            //3.反射实现方法的调用
            meth.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
